<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\QrCodeController;
use App\Models\AnswerActivity;
use App\Models\AnswerActivityArea;
use App\Models\AnswerActivityBrowseCount;
use App\Models\AnswerActivityGift;
use App\Models\AnswerActivityGiftPublic;
use App\Models\AnswerActivityInvite;
use App\Models\AnswerActivityProblem;
use App\Models\AnswerActivityResource;
use App\Models\AnswerActivityShare;
use App\Models\AnswerActivityUnit;
use App\Models\AnswerActivityUnitUserNumber;
use App\Models\AnswerActivityUserAnswerRecord;
use App\Models\AnswerActivityUserAnswerTotalNumber;
use App\Models\AnswerActivityUserCorrectAnswerRecord;
use App\Models\AnswerActivityUserCorrectNumber;
use App\Models\AnswerActivityUserCorrectTotalNumber;
use App\Models\AnswerActivityUserGift;
use App\Models\AnswerActivityUserPrize;
use App\Models\AnswerActivityUserPrizeRecord;
use App\Models\AnswerActivityUserStairsAnswerRecord;
use App\Models\AnswerActivityUserStairsTotalNumber;
use App\Models\AnswerActivityUserUnit;
use App\Models\AnswerActivityUserUsePrizeRecord;
use App\Models\Manage;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 活动类
 */
class AnswerActivityController extends CommonController
{
    protected $model;
    protected $validate;

    public function __construct()
    {
        parent::__construct();

        $this->model = new \App\Models\AnswerActivity();
        $this->validate = new  \App\Validate\AnswerActivityValidate();
    }

    /**
     * 获取活动类型
     */
    public function getNodeName()
    {
        $data = $this->model->getNodeName();
        $config_node = config('other.answer_activity_node');

        $new_data = [];
        $i = 0;
        foreach ($data as $key => $val) {
            if (in_array($key, $config_node)) {
                $new_data[$i]['id'] = $key;
                $new_data[$i]['name'] = $val;
                $i++;
            }
        }

        if ($new_data) {
            return $this->returnApi(200, "获取成功", true, $new_data);
        }
        return $this->returnApi(203, "暂无数据");
    }

    /**
     * 获取答题模式  1  馆内答题形式  2 轮次排名形式 （按轮次排名）  3 爬楼梯形式
     */
    public function getPatternName()
    {
        $data = $this->model->getPatternName();
        $config_node = config('other.answer_activity_pattern');
        $new_data = [];
        $i = 0;
        foreach ($data as $key => $val) {
            if (in_array($key, $config_node)) {
                $new_data[$i]['id'] = $key;
                $new_data[$i]['name'] = $val;
                $i++;
            }
        }
        if ($new_data) {
            return $this->returnApi(200, "获取成功", true, $new_data);
        }
        return $this->returnApi(203, "暂无数据");
    }

    /**
     * 获取获奖情况  1 排名  2 抽奖
     */
    public function getPrizeFormName()
    {
        $data = $this->model->getPrizeFormName();
        $config_node = config('other.answer_activity_prize_form');
        $new_data = [];
        $i = 0;
        foreach ($data as $key => $val) {
            if (in_array($key, $config_node)) {
                $new_data[$i]['id'] = $key;
                $new_data[$i]['name'] = $val;
                $i++;
            }
        }
        if ($new_data) {
            return $this->returnApi(200, "获取成功", true, $new_data);
        }
        return $this->returnApi(203, "暂无数据");
    }


    /**
     * 列表
     * @param page int 页码
     * @param limit int 分页大小
     * @param is_play string 是否发布   1 已发布  2 未发布
     * @param keywords string 搜索关键词
     * @param start_time datetime 活动开始时间    数据格式  年月日
     * @param end_time datetime 活动结束时间
     * @param node int 活动类型    1 独立活动  2 单位联盟   3 区域联盟
     * @param pattern int 答题模式  1  馆内答题形式  2 轮次排名形式 （按轮次排名）  3 爬楼梯形式
     * @param prize_form int 获奖情况  1 排名  2 抽奖
     *
     * @param create_start_time datetime 活动创建开始时间   数据格式 年月日时分秒
     * @param create_end_time datetime 活动创建结束时间
     */
    public function lists()
    {
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $create_start_time = $this->request->create_start_time;
        $create_end_time = $this->request->create_end_time;
        $is_play = $this->request->is_play;
        $node = $this->request->node;
        $pattern = $this->request->pattern;
        $prize_form = $this->request->prize_form;

        $res = $this->model->lists(null, $keywords, $is_play, $node, $pattern, $prize_form, $start_time, $end_time, $create_start_time, $create_end_time, $page, $limit);

        if ($res['total'] == 0 || !$res['data']) {
            return $this->returnApi(203, "暂无数据");
        }

        foreach ($res['data'] as $key => $val) {
            // $res['data'][$key]['intro'] = str_replace('&nbsp;' , '', strip_tags($val['intro']));
            $res['data'][$key]['rule'] = $val['rule_type'] == 1 ? str_replace('&nbsp;', '', strip_tags($val['rule'])) : $val['rule'];
            $res['data'][$key]['status'] = $this->model->getActListStatus($val);

            $res['data'][$key]['node_name'] = $this->model->getNodeName($val['node']);
            $res['data'][$key]['pattern_name'] = $this->model->getPatternName($val['pattern']);
            $res['data'][$key]['prize_form_name'] = $this->model->getPrizeFormName($val['prize_form']);

            $res['data'][$key]['manage_name'] = Manage::getManageNameByManageId($val['manage_id']);

            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);

            $res['data'][$key]['is_have_gift'] = $val['prize_form'] == 2 ? (AnswerActivityGift::isHaveGift($val['id']) === true ? true : false) : false; //是否配置礼物
            $res['data'][$key]['is_have_gift_public'] = $val['prize_form'] == 2 ? (AnswerActivityGiftPublic::isHaveGiftPublic($val['id']) === true ? true : false) : false; //是否配置礼物

            $res['data'][$key]['is_have_area'] = $val['node'] == 3 ? (AnswerActivityArea::isHaveArea($val['id']) === true ? true : false) : false; //是否有区域
            $res['data'][$key]['is_have_unit'] = $val['node'] == 2 || $val['node'] == 3 ? (AnswerActivityUnit::isHaveUnit($val['id']) === true ? true : false) : false; //是否有单位
            $res['data'][$key]['is_have_color'] = true;
            $res['data'][$key]['is_have_img'] = true;
            $answerActivityResource = new AnswerActivityResource();
            $color_info = $answerActivityResource->detail($val['id'], null, null);

            if (empty($color_info)) {
                $res['data'][$key]['is_have_color'] = false;
                $res['data'][$key]['is_have_img'] = false;
            } else {
                if (empty($color_info['resource_path'])) {
                    $res['data'][$key]['is_have_img'] = false;
                }
                if (empty($color_info['theme_color'])) {
                    $res['data'][$key]['is_have_color'] = false;
                }
            }

            $model = $this->model->getAnswerRecordModel($val['pattern']);
            $isBeenAnswer = $model->isBeenAnswer($val['id']);
            $res['data'][$key]['is_been_answer'] = $isBeenAnswer ? true : false; //是否有人答题，没人答题才可以删除

            $res['data'][$key]['is_have_problem'] = AnswerActivityProblem::isHaveProblem($val['id']) === true ? true : false; //是否配置问题
        }

        $res = $this->disPageData($res);
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int 活动id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->where('id', $this->request->id)->where('is_del', 1)->first();

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }

        $real_info_array = $this->model->getAnswerActivityApplyParam();
        $res->real_info_value = $this->getRealInfoArray($res->real_info, $real_info_array, 'value');
        $res->real_info_value = join("|", $res->real_info_value);
        // if ($res->real_info) {
        //     $real_info = explode("|", $res->real_info);

        //     $real_info_value = [];
        //     foreach ($real_info as $key => $val) {
        //         $temp = isset($real_info_array[$val - 1]) ? $real_info_array[$val - 1]['value'] : '';
        //         $real_info_value[] = $temp;
        //     }

        //     $res->real_info_value = implode("|", $real_info_value);
        // } else {
        //     $res->real_info_value = null;
        // }

        $res = $res->toArray();
        $model = $this->model->getAnswerRecordModel($res['pattern']);
        $isBeenAnswer = $model->isBeenAnswer($this->request->id);
        $res['is_been_answer'] = $isBeenAnswer ? true : false; //是否有人答题，没人答题就可以修改

        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 新增
     * @param title string 活动名称
     * @param img string 活动封面
     * @param node int 活动类型    1 独立活动  2 单位联盟   3 区域联盟
     * @param is_show_list int 是否显示列表 1显示 2 不显示  单位联盟 是否显示单位列表  区域联盟 是否显示区域和单位列表
     * @param is_show_small_rank int 是否显示分馆排名列表 1显示 2 不显示  轮次排名才有效
     * @param pattern int 答题模式  1  馆内答题形式  2 轮次排名形式 （按轮次排名）  3 爬楼梯形式
     * @param prize_form int 获奖情况  1 排名  2 抽奖
     * @param real_info string  选填 如果不是阅享用户则必填   填写信息  如果是阅享用户，则无效    1、姓名  2、电话   3、身份证号码  4、读者证   多个  | 连接
     * @param is_need_unit int 是否需要选择图书馆   1 需要  2 不需要 （单活动模式，默认不需要）
     * @param total_floor int 爬楼梯梯模式，总楼层
     * @param number int 每日答题次数    除轮次外 （一轮为一次，不管有多少题），其余一道题就是一次
     * @param answer_number int 除轮次排名外（每次（轮）多少题）,单纯排名不需要此参数，其余都是多少题获得一次抽奖机会，馆内答题就是馆内答题数量
     * @param is_loop int 是否可以循环，只对 场馆答题 有效    1可以   2 不可以
     * @param share_number int 分享获取答题次数，每日几次
     * @param answer_time int 每题答题时间   单位 秒      轮次排名为总时间
     * @param answer_rule 答题规则   1、专属题和公共题 混合  2、优先回答专属题
     * @param rule_type int 规则方式   1 内容   2外链
     * @param rule  规则内容     rule_type  为1 这里是编辑器内容   2 这里是链接
     * @param start_time datetime 活动开始时间
     * @param end_time datetime 活动结束时间
     * @param answer_start_time datetime 开始答题时间
     * @param answer_end_time datetime 结束答题时间
     * @param lottery_start_time datetime 抽奖开始时间
     * @param lottery_end_time datetime 抽奖结束时间
     * @param invite_code string 邀请码  6位
     * @param share_title string 分享标题
     * @param share_img string 分享图片
     * @param is_show_address string 前端界面是否填写地址 1 需要  2 不需要
     * @param is_reset_data string 答题开始时自动重置数据（答题时间开始后，无法修改此参数，系统自动修改为不自动重置） 1 重置  2 不重置

    // * @param slogan1 string 我的成绩单 slogan1    去掉
    // * @param slogan2 string 我的成绩单 slogan2    去掉
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        if ($this->request->pattern == 3 && empty($this->request->total_floor)) {
            return $this->returnApi(202, "总楼层不能为空");
        }
        if ($this->request->pattern == 3 && $this->request->prize_form == 2 && empty($this->request->answer_number)) {
            return $this->returnApi(202, "获取奖票间隔数不能为空");
        }
        if ($this->request->pattern == 2 && $this->request->prize_form == 1 && empty($this->request->answer_number)) {
            return $this->returnApi(202, "每轮题目数量不能为空");
        }
        if ($this->request->pattern == 1 && empty($this->request->answer_number)) {
            return $this->returnApi(202, "馆内答题数量不能为空");
        }
        if (!empty($this->request->share_title) && mb_strlen($this->request->share_title) > 12) {
            return $this->returnApi(202, "分享标题文字不能超过12个字");
        }
        $is_exists = $this->model->nameIsExists($this->request->title, 'title');

        if ($is_exists) {
            return $this->returnApi(202, "该活动名称已存在");
        }
        if ($this->request->invite_code && strlen($this->request->invite_code) != 6) {
            return $this->returnApi(202, "活动邀请码必须是6位");
        }

        if ($this->request->prize_form == 2 && (!$this->request->lottery_start_time || !$this->request->lottery_end_time)) {
            return $this->returnApi(201, "请填写活动抽奖时间");
        }

        //生成二维码
        $qrCodeObj = new QrCodeController();
        $qr_code = $qrCodeObj->getQrCode('answer_activity');
        if ($qr_code === false) {
            Log::error("答题活动二维码生成失败,请手动生成");
            return $this->returnApi(201, "二维码生成失败");
        }
        $qr_data = $this->getDomainName() . '/' . config('other.project_name') . 'wx/pGames/gameLoading/index?from=readshare_activity&token=' . $qr_code; //二维码的链接  扫码跳转二维码
        $qr_url = $qrCodeObj->setQr($qr_data, true, 360, 1);

        // 启动事务
        DB::beginTransaction();
        try {
            $data = [
                'title' => $this->request->title,
                'img' => $this->request->img ? $this->request->img : 'default/default_activity.png',
                'node' => $this->request->node,
                'pattern' => $this->request->pattern,
                'prize_form' => $this->request->prize_form,
                'is_ushare' => !empty(config('other.is_ushare')) ? config('other.is_ushare') : 2,
                'real_info' => empty(config('other.is_ushare')) || config('other.is_ushare') == 2 ? $this->request->real_info : null,
                'is_need_unit' => $this->request->is_need_unit,
                'total_floor' => $this->request->total_floor,
                'number' => $this->request->number,
                'answer_number' => $this->request->answer_number,
                'is_show_list' => $this->request->node != 1 ? $this->request->is_show_list : 2, //1显示 2 不显示
                'is_show_small_rank' => $this->request->pattern == 2 ? $this->request->is_show_small_rank : 2, //1显示 2 不显示
                'is_loop' => $this->request->pattern ? $this->request->is_loop : null,

                'share_number' => $this->request->share_number ? $this->request->share_number : 0,
                'answer_time' => $this->request->answer_time,
                'answer_rule' => $this->request->answer_rule,
                'rule_type' => $this->request->rule_type,
                'rule' => $this->request->rule,

                'start_time' => $this->request->start_time,
                'end_time' => $this->request->end_time,
                'answer_start_time' => $this->request->answer_start_time,
                'answer_end_time' => $this->request->answer_end_time,
                'lottery_start_time' => $this->request->lottery_start_time ? $this->request->lottery_start_time : null,
                'lottery_end_time' => $this->request->lottery_end_time ? $this->request->lottery_end_time : null,

                'manage_id' => $this->request->manage_id,
                'invite_code' => $this->request->invite_code,
                'share_title' => $this->request->share_title,
                'share_img' => $this->request->share_img,
                'is_show_address' => $this->request->is_show_address ? $this->request->is_show_address : 1,
                'qr_code' => $qr_code,
                'qr_url' => $qr_url,
                //  'slogan1' => $this->request->slogan1,
                //   'slogan2' => $this->request->slogan2,
            ];

            if ($this->request->is_reset_data == 1 && $this->request->answer_end_time > date('Y-m-d H:i:s')) {
                $is_reset_data = 1;
            } else {
                $is_reset_data = 2; //不允许重置
            }
            $data['is_reset_data'] = $is_reset_data;
            $this->model->add($data);
            //生成存放资源路径
            $activityResourceModel = new AnswerActivityResource();
            $activityResourceModel->createImgStoreDir($this->model->id);

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "新增成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }



    /**
     * 修改
     * @param id string 活动id
     * @param title string 活动名称
     * @param img string 活动封面
     * @param node int 活动类型    1 独立活动  2 单位联盟   3 区域联盟    （无人答题之前，都可以修改）
     * @param pattern int 答题模式  1  馆内答题形式  2 轮次排名形式 （按轮次排名）  3 爬楼梯形式
     * @param prize_form int 获奖情况  1 排名  2 抽奖
     * @param real_info string  选填 如果不是阅享用户则必填   填写信息  如果是阅享用户，则无效    1、姓名  2、电话   3、身份证号码  4、读者证   多个  | 连接
     * @param is_need_unit int 是否需要选择图书馆   1 需要  2 不需要 （单活动模式，默认不需要）
     * @param total_floor int 爬楼梯梯模式，总楼层
     * @param is_show_list int 是否显示列表 1显示 2 不显示  单位联盟 是否显示单位列表  区域联盟 是否显示区域和单位列表
     * @param is_show_small_rank int 是否显示分馆排名列表 1显示 2 不显示  轮次排名才有效
     * @param number int 每日答题次数    除轮次外 （一轮为一次，不管有多少题），其余一道题就是一次
     * @param answer_number int 除轮次排名外（每次（轮）多少题）,单纯排名不需要此参数，其余都是多少题获得一次抽奖机会,馆内答题就是馆内答题数量
     * @param is_loop int 是否可以循环，只对 场馆答题 有效    1可以   2 不可以
     * @param share_number int 分享获取答题次数，每日几次
     * @param answer_time int 每题答题时间   单位 秒   轮次排名为总时间
     * @param answer_rule 答题规则   1、专属题和公共题 混合  2、优先回答专属题
     * @param rule_type int 规则方式   1 内容   2外链
     * @param rule  规则内容     rule_type  为1 这里是编辑器内容   2 这里是链接
     * @param start_time datetime 活动开始时间
     * @param end_time datetime 活动结束时间
     * @param answer_start_time datetime 开始答题时间
     * @param answer_end_time datetime 结束答题时间
     * @param lottery_start_time datetime 抽奖开始时间
     * @param lottery_end_time datetime 抽奖结束时间
     * @param invite_code string 邀请码  6位
     * @param share_title string 分享标题
     * @param share_img string 分享图片
     * @param is_show_address string 前端界面是否填写地址 1 需要  2 不需要
     * @param is_reset_data string 答题开始时自动重置数据（答题时间开始后，无法修改此参数，系统自动修改为不自动重置） 1 重置  2 不重置


    // * @param slogan1 string 我的成绩单 slogan1
   //  * @param slogan2 string 我的成绩单 slogan2
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        if ($this->request->pattern == 3 && empty($this->request->total_floor)) {
            return $this->returnApi(202, "总楼层不能为空");
        }

        if ($this->request->pattern == 3 && $this->request->prize_form == 2 && empty($this->request->answer_number)) {
            return $this->returnApi(202, "获取奖票间隔数不能为空");
        }
        if ($this->request->pattern == 2 && $this->request->prize_form == 1 && empty($this->request->answer_number)) {
            return $this->returnApi(202, "每轮题目数量不能为空");
        }
        if ($this->request->pattern == 1 && empty($this->request->answer_number)) {
            return $this->returnApi(202, "馆内答题数量不能为空");
        }
        if (!empty($this->request->share_title) && mb_strlen($this->request->share_title) > 12) {
            return $this->returnApi(202, "分享标题文字不能超过12个字");
        }
        $id = $this->request->id;
        $res = $this->model->where('id', $id)->where('is_del', 1)->first();
        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }
        if ($res->is_play == 1) {
            return $this->returnApi(201, "请先撤销，在进行修改！");
        }

        //判断是否可以修改是否循环模式
        //判断是否有人答题
        // $activityModel = new AnswerActivity();
        $model = $this->model->getAnswerRecordModel($res['pattern']);
        $isBeenAnswer = $model->isBeenAnswer($this->request->id);
        if ($isBeenAnswer) {
            if ($res->is_loop != $this->request->is_loop) {
                return $this->returnApi(202, "此活动已有用户参与，不允许切换循环模式");
            }
            if ($this->request->answer_number != $res->answer_number) {
                return $this->returnApi(202, "此活动已有用户参与，答题数量不允许修改");
            }
            if ($this->request->node != $res->node) {
                return $this->returnApi(202, "此活动已有用户参与，活动类型不允许修改");
            }
            if ($this->request->pattern != $res->pattern) {
                return $this->returnApi(202, "此活动已有用户参与，答题模式不允许修改");
            }
            if ($this->request->prize_form != $res->prize_form) {
                return $this->returnApi(202, "此活动已有用户参与，获奖情况不允许修改");
            }
        }

        $is_exists = $this->model->nameIsExists($this->request->title, 'title', $this->request->id);

        if ($is_exists) {
            return $this->returnApi(202, "该活动名称已存在");
        }
        if ($this->request->invite_code && strlen($this->request->invite_code) != 6) {
            return $this->returnApi(202, "活动邀请码必须是6位");
        }

        if ($this->request->prize_form == 2 && (!$this->request->lottery_start_time || !$this->request->lottery_end_time)) {
            return $this->returnApi(201, "请填写活动抽奖时间");
        }

        $old_img = $res->img;

        // 启动事务
        DB::beginTransaction();
        try {
            $data = [
                'id' => $this->request->id,
                'title' => $this->request->title,
                'img' => $this->request->img ? $this->request->img : 'default/default_activity.png',
                'node' => $this->request->node,
                'pattern' => $this->request->pattern,
                'prize_form' => $this->request->prize_form,
                'is_ushare' => !empty(config('other.is_ushare')) ? config('other.is_ushare') : 2,
                'real_info' => empty(config('other.is_ushare')) || config('other.is_ushare') == 2 ? $this->request->real_info : null,
                'is_need_unit' => $this->request->is_need_unit,
                'total_floor' => $this->request->total_floor,
                'number' => $this->request->number,
                'answer_number' => $this->request->answer_number,
                'is_show_list' => $this->request->node != 1 ? $this->request->is_show_list : 2, //1显示 2 不显示
                'is_show_small_rank' => $this->request->pattern == 2 ? $this->request->is_show_small_rank : 2, //1显示 2 不显示
                'is_loop' => $res->pattern ? $this->request->is_loop : null,

                'share_number' => $this->request->share_number,
                'answer_time' => $this->request->answer_time,
                'answer_rule' => $this->request->answer_rule,
                'rule_type' => $this->request->rule_type,
                'rule' => $this->request->rule,

                'start_time' => $this->request->start_time,
                'end_time' => $this->request->end_time,
                'answer_start_time' => $this->request->answer_start_time,
                'answer_end_time' => $this->request->answer_end_time,
                'lottery_start_time' => $this->request->lottery_start_time ? $this->request->lottery_start_time : null,
                'lottery_end_time' => $this->request->lottery_end_time ? $this->request->lottery_end_time : null,

                'invite_code' => $this->request->invite_code,
                'share_title' => $this->request->share_title,
                'is_show_address' => $this->request->is_show_address ? $this->request->is_show_address : 1,
                'share_img' => $this->request->share_img,
                //    'slogan1' => $this->request->slogan1,
                //   'slogan2' => $this->request->slogan2,
            ];


            if (empty($res['qr_url'])) {
                //生成二维码
                $qrCodeObj = new QrCodeController();
                if (empty($res['qr_code'])) {
                    $qr_code = $qrCodeObj->getQrCode('answer_activity');
                    if ($qr_code === false) {
                        Log::error("答题活动二维码生成失败,请手动生成");
                        throw new Exception("二维码生成失败");
                    }
                } else {
                    $qr_code = $res['qr_code'];
                }
                $qr_data = $this->getDomainName() . '/' . config('other.project_name') . 'wx/pGames/gameLoading/index?from=readshare_activity&token=' . $qr_code; //二维码的链接  扫码跳转二维码
                $qr_url = $qrCodeObj->setQr($qr_data, true, 360, 1);; //减小容错，让二维码更简单
                $data['qr_url'] = $qr_url;
                $data['qr_code'] = $qr_code;
            }

            if ($this->request->is_reset_data == 1 && $this->request->answer_end_time > date('Y-m-d H:i:s')) {
                $is_reset_data = 1;
            } else {
                $is_reset_data = 2; //不允许重置
            }
            $data['is_reset_data'] = $is_reset_data;
            $this->model->change($data);

            //删除旧资源
            if ($old_img != $this->request->img && $old_img != 'default/default_activity.png') {
                $this->deleteFile($old_img);
            }

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, "修改失败");
        }
    }

    /**
     * 删除
     * @param id int 活动id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->model->detail($this->request->id, null, null);

        if (empty($res)) {
            return $this->returnApi(201, "参数传递错误");
        }
        //判断是否有人答题
        //  $activityModel = new AnswerActivity();
        //  $model = $activityModel->getAnswerRecordModel($res['pattern']);
        // $isBeenAnswer = $model->isBeenAnswer($res->pattern, $this->request->id);
        // $activityModel = new AnswerActivity();
        $model = $this->model->getAnswerRecordModel($res['pattern']);
        $isBeenAnswer = $model->isBeenAnswer($this->request->id);

        if ($isBeenAnswer) {
            return $this->returnApi(202, "此活动已有用户参与，不允许删除");
        }

        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }



    /**
     * 撤销 和发布
     * @param id int 活动id
     * @param is_play int 发布   1 发布  2 撤销
     */
    public function cancelAndRelease()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('cancel_and_release')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        //判断是否符合发布的条件
        if ($this->request->is_play == 1) {
            $is_can_play = $this->model->isCanPlay($this->request->id);
            if ($is_can_play !== true) {
                return $this->returnApi(202, $is_can_play);
            }
        }

        DB::beginTransaction();
        try {
            list($code, $msg) = $this->model->resumeAndCancel($this->request->id, 'is_play', $this->request->is_play);

            $is_play = $this->request->is_play == 1 ? '发布' : '撤销';

            DB::commit();
            return $this->returnApi($code, $is_play . $msg, $code === 200 ? true : false);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 邀请码修改
     * @param id int 活动id
     * @param invite_code int 邀请码  6 位纯数字
     */
    public function invitCodeChange()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('invite_code_change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->model->find($this->request->id);
        if (empty($res)) {
            return $this->returnApi(202, '参数传递错误');
        }
        DB::beginTransaction();
        try {
            $res->invite_code = $this->request->invite_code;
            $res->save();

            DB::commit();
            return $this->returnApi(200, '修改成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 设置答题总规则  (弃用，在活动里面统一设置)
     * @param act_id 活动id
     * @param answer_rule 答题规则   1、专属题和公共题 混合  2、优先回答专属题
     */
    public function set_answer_rule()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('get_answer_rule')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->model->find($this->request->id);
        if (empty($res)) {
            return $this->returnApi(202, '参数传递错误');
        }

        $res->answer_rule = $this->request->answer_rule;
        $result = $res->save();
        if ($result) {
            return $this->returnApi(200, '设置成功');
        }
        return $this->returnApi(200, '设置失败');
    }

    /**
     * 重置数据
     * @param act_id 活动id
     * @param password  管理员密码
     */
    public function resetData()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('reset_data')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        //判断管理员密码是否正确
        $is_success = Manage::passwordIsSuccess($this->request->manage_id, $this->request->password);
        if (!$is_success) {
            return $this->returnApi(202, '密码输入错误');
        }
        $res = $this->model->where('id', $this->request->act_id)->where('is_del', 1)->first();
        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }
        if ($res['is_play'] == 1) {
            return $this->returnApi(202, "此活动未撤销，请先撤销");
        }
        if ($res['start_time'] < date('Y-m-d H:i:s')) {
            return $this->returnApi(202, "此活动已开始，不允许重置");
        }
        DB::beginTransaction();
        try {
            Log::error('开始重置数据,活动id：' . $this->request->act_id . '；管理员id：' . $this->request->manage_id);
            //直接重置数据
            $this->model->resetData($this->request->act_id);

            Log::error('重置数据成功,活动id：' . $this->request->act_id . '；管理员id：' . $this->request->manage_id);

            DB::commit();
            return $this->returnApi(200, "重置成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, "重置失败");
        }
    }
    /**
     * 复制活动
     * @param act_id 活动id
     * @param password  管理员密码
     */
    public function copyData()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('copy_data')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        //判断管理员密码是否正确
        $is_success = Manage::passwordIsSuccess($this->request->manage_id, $this->request->password);
        if (!$is_success) {
            return $this->returnApi(202, '密码输入错误');
        }
        $res = $this->model->where('id', $this->request->act_id)->where('is_del', 1)->first();
        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }
        $res = $res->toArray();
        unset($res['id']);
        unset($res['browse_num']);
        unset($res['create_time']);
        unset($res['change_time']);
        unset($res['qr_code']);
        unset($res['qr_url']);

        //生成二维码
        $qrCodeObj = new QrCodeController();
        $qr_code = $qrCodeObj->getQrCode('answer_activity');
        if ($qr_code === false) {
            Log::error("二维码生成失败,请手动生成");
            return $this->returnApi(201, "二维码生成失败");
        }
        $qr_data = $this->getDomainName() . '/' . config('other.project_name') . 'wx/pGames/gameLoading/index?from=readshare_activity&token=' . $qr_code; //二维码的链接  扫码跳转二维码
        $qr_url = $qrCodeObj->setQr($qr_data, true, 360, 1);

        DB::beginTransaction();
        try {
            $res['qr_code'] = $qr_code; //重新生成二维码
            $res['qr_url'] = $qr_url;
            $res['manage_id'] = $this->request->manage_id;
            $res['is_play'] = 2; //默认未发布
            $this->model->add($res);

            DB::commit();
            return $this->returnApi(200, "复制成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, "复制失败");
        }
    }
}
